package com.lz.aspect;

import com.lz.annotation.ExecuteTime;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Aspect
@Component
@Slf4j
public class ExecuteTimeAspect {


    @Pointcut("@annotation(executeTime)")
    public void serviceExecutionTimeLog(ExecuteTime executeTime) {
    }

    @Around(value = "serviceExecutionTimeLog(executeTime)", argNames = "proceedingJoinPoint,executeTime")
    public Object doBefore(ProceedingJoinPoint proceedingJoinPoint, ExecuteTime executeTime) throws Throwable {
//        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
//        ExecuteTime annotation = signature.getMethod().getAnnotation(ExecuteTime.class);
        String functionName = executeTime.name();
//        if(functionName.isEmpty()){
//            functionName = signature.getMethod().getName();
//        }
        long start = System.currentTimeMillis();
        Object proceed = null;
        try {
            proceed = proceedingJoinPoint.proceed();
        }catch (Exception e){
            log.error(e.toString());
        }
        long end = System.currentTimeMillis();
        long timeUse = end - start;
        log.info(functionName +"  调用时间 "+timeUse+" ms");
        return proceed;
    }



    @Around(value = "serviceExecutionTimeLog(executeTime)", argNames = "proceedingJoinPoint,executeTime")
    public Object doAfter(ProceedingJoinPoint proceedingJoinPoint, ExecuteTime executeTime) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object proceed = proceedingJoinPoint.proceed();
        stopWatch.stop();

        log.info("execute-time-name : [{}], execution-time : [{}], class-method : [{}]", executeTime.name(),
                stopWatch.getTotalTimeMillis(),
                proceedingJoinPoint.getTarget().getClass().getName() + "." + proceedingJoinPoint.getSignature().getName());


        return proceed;
    }
}
